<?php


class STE {
	private $template_raw = NULL;
	private $template_rendered = NULL;

	function __init__ ($template_name = "") {
		if ( ! empty ( $template_name ) ) {
			$this->load($template_name);
		}
	}

	function handle_exception($e) {
		print '<pre>';
			print_r($e);
		print '</pre>';
	}

	function load($template_name) {
		try {
			$filename = sprintf("%s/templates/%s.tpl", YOULOC_DATA, $template_name);
			if ( ! file_exists($filename) ) {
				throw new Exception("Template not found");
			} else {
				$this->template_raw = file_get_contents($filename);
			}
			$this->process_template();
		} catch (Exception $e) {
			$this->handle_exception($e);
		}
	}

	function process_template () {
		$template = $this->template_raw;
		preg_match_all("/<!--@IMPORT:(.*?)@-->/",$template, $m);
		foreach ($m[1] as $include_template) {
			$template = new STE();
			$template->load($include_template);
			$this->template_raw = str_replace(sprintf("<!--@IMPORT:%s@-->",$include_template), $template->template_raw, $this->template_raw);
		}

	}

	function assign($variables = array() ) {
		$from = array();
		$to = array();
		while (list($key,$data) = each($variables)) {
			$from[] = sprintf("<!--@%s@-->",$key);
			$to[] = $data;
		}
		$this->template_rendered = str_replace($from, $to, $this->template_raw);
	}

	function display () {
		$template_data = NULL;
		if ($this->template_rendered == "") {
			$template_data = $this->template_raw;
		} else {
			$template_data = $this->template_rendered;
		}
		$template_data = preg_replace("/<!--.*?-->/i","", $template_data);

		return $template_data;
	}

}

?>
